const mysql = require('../../utils/db');
const BaseModel = require('../BaseModel');
const _table_name = "music_album";

exports.findAll = (success, fail, _all = false) => {
    let order = " ORDER BY album_id DESC";
    let sqlStr = `
    SELECT
        a.*, IFNULL(s.singer_name,'未知歌手') as singer_name
    FROM
        ${_table_name} a
    LEFT JOIN singer s ON (
        a.singer_id = s.singer_id
    )
    ${_all ? "" : "WHERE album_id !='0' "} 
    ${order}
    `;
    return mysql.row(sqlStr)
        .then(data => {
            success(data);
        })
        .catch(err => {
            fail(err);
        });
}

exports.updateMusicAlbum = async (params, updatekey, success, fail) => {
    let sqlStr = BaseModel.update(_table_name, params, updatekey);

    return mysql.row(sqlStr)
        .then(data => {
            success(data);
        })
        .catch(err => {
            fail(err);
        });
}

exports.findMusicAlbum = async (params) => {
    this.data = null;
    this.err = null;
    let sqlStr = BaseModel.find(_table_name, params);

    await mysql.row(sqlStr)
        .then(data => {
            this.data = data;
        })
        .catch(err => {
            this.err = err;
        });

    this.success = (fn) => {
        if (this.data)
            return fn(this.data);
    }
    this.fail = (fn) => {
        if (this.err)
            return fn(this.err);
    }
    return this;
}

exports.delMusicAlbum = (params, success, fail) => {
    let sqlStr = BaseModel.delete(_table_name, params);
    return mysql.row(sqlStr)
        .then(data => {
            success(data);
        })
        .catch(err => {
            fail(err);
        });
}

exports.addMusicAlbum = (params, success, fail) => {
    let sqlStr = BaseModel.add(_table_name, params);
    return mysql.row(sqlStr)
        .then(data => {
            success(data);
        })
        .catch(err => {
            fail(err);
        });
}